﻿Imports Microsoft.VisualBasic

Namespace WebApi
    Namespace Buffer
        Public Class BufferClient

            Private webClient As WebApi.Net.WebClient

            Public Sub New(oauth2 As WebApi.Oauth.Oauth2)

                Me.webClient = New WebApi.Net.WebClient
                Me.webClient.oAuth2 = oauth2

            End Sub

            Public Property LastError As Net.ServiceError
            Private Function Download(address As String) As String

                Me.LastError = New Net.ServiceError With {
                    .webClient = Me.webClient,
                    .Net = WebApi.Type.BUFFER
                }

                Dim Res = ""
                Dim TryDonwload = 0
                Do
                    Try
                        Res = Encoding.UTF8.GetString(Me.webClient.DownloadData(address))
                        TryDonwload = 0

                    Catch ex As Exception

                        TryDonwload += 1

                        MyApp.WriteProcLog(SF("!!! CONNECT ERROR !!! errore n:{0} - {1} - {2}", TryDonwload, ex.Message, Me.webClient.RequestUri.AbsolutePath), MyApp.Task.TaskType.NET_CONNECT)

                        Me.LastError.ResError = "!!! CONNECT ERROR !!!"
                        Me.LastError.Code = -1
                        Me.LastError.Message = ex.Message

                    End Try

                    Select Case Me.webClient.StatusCode

                        Case 500, 502, 503, 504

                            TryDonwload += 1

                            MyApp.WriteProcLog(SF("!!! SERVER ERROR !!! errore n:{0} - {1} - {2}", TryDonwload, Res), MyApp.Task.TaskType.NET_API)

                            Me.LastError.ResError = Res
                            Me.LastError.Code = Me.webClient.StatusCode
                            Me.LastError.Message = Me.webClient.StatusCodeDescr

                    End Select

                    Select Case TryDonwload
                        Case 1
                            Threading.Thread.Sleep(2000)
                        Case 2
                            Threading.Thread.Sleep(10000)
                        Case 3
                            Threading.Thread.Sleep(20000)
                        Case 4
                            Threading.Thread.Sleep(60000)
                        Case Is > 4

                            If Me.LastError.Code < 0 Then
                                Net.ExceptionBase.ThrowException(New Net.ExceptionConnectionNetwork With {.ServiceError = Me.LastError})
                            Else
                                Net.ExceptionBase.ThrowException(New Net.ExceptionConnectionServer With {.ServiceError = Me.LastError})
                            End If

                    End Select


                Loop Until TryDonwload = 0

                webClient.postParams.Clear()
                webClient.Multipart = False

                If Me.webClient.StatusCode <> 200 Then

                    Me.LastError.ResError = Res


                    Try
                        Dim Err As ServiceError
                        Err = MyApp.JSONDeserializeObj(Of ServiceError)(Res)

                        Me.LastError.Code = Err.code
                        Me.LastError.Message = Err.message

                    Catch ex As Exception

                        Me.LastError.Code = Me.webClient.StatusCode
                        Me.LastError.Message = Res

                    End Try

                    'https://bufferapp.com/developers/api/errors
                    Select Case Me.webClient.StatusCode

                        Case 400
                            Net.ExceptionBase.ThrowException(New Net.ExceptionAPIResponse With {.ServiceError = Me.LastError})


                        Case 403
                            Net.ExceptionBase.ThrowException(New Net.ExceptionAPIAccount With {.ServiceError = Me.LastError})

                    End Select




                    'End Select

                    Net.ExceptionBase.ThrowException(New Net.ExceptionBase With {.ServiceError = Me.LastError})

                End If


                Return Res

            End Function
            Private Function Download_old(address As String) As String

                Me.LastError = New Net.ServiceError With {
                    .webClient = Me.webClient,
                    .Net = WebApi.Type.BUFFER
                }

                Dim Res = ""
                Dim TryDonwload = 0
                Do
                    Try
                        Res = Encoding.UTF8.GetString(Me.webClient.DownloadData(address))
                        TryDonwload = 0
                    Catch ex As Exception

                        TryDonwload += 1

                        MyApp.WriteProcLog(SF("!!! CONNECT ERROR !!! errore n:{0} - {1} - {2}", TryDonwload, ex.Message, Me.webClient.RequestUri.AbsolutePath), MyApp.Task.TaskType.NET_CONNECT)

                        Select Case TryDonwload
                            Case 1
                                Threading.Thread.Sleep(2000)
                            Case 2
                                Threading.Thread.Sleep(10000)
                            Case 3
                                Threading.Thread.Sleep(20000)
                            Case 4
                                Threading.Thread.Sleep(60000)
                            Case Else

                                Me.LastError.ResError = "!!! CONNECT ERROR !!!"
                                Me.LastError.Code = -1
                                Me.LastError.Message = ex.Message
                                Net.ExceptionBase.ThrowException(New Net.ExceptionConnectionNetwork With {.ServiceError = Me.LastError})

                        End Select

                    End Try

                    Select Case Me.webClient.StatusCode

                        Case 500, 502, 503, 504

                            TryDonwload += 1

                            MyApp.WriteProcLog(SF("!!! SERVER ERROR !!! errore n:{0} - {1} - {2}", TryDonwload, Res), MyApp.Task.TaskType.NET_API)


                            Select Case TryDonwload
                                Case 1
                                    Threading.Thread.Sleep(2000)
                                Case 2
                                    Threading.Thread.Sleep(10000)
                                Case 3
                                    Threading.Thread.Sleep(20000)
                                Case 4
                                    Threading.Thread.Sleep(60000)
                                Case Else

                                    Me.LastError.ResError = Res
                                    Me.LastError.Code = Me.webClient.StatusCode
                                    Me.LastError.Message = Me.webClient.StatusCodeDescr

                                    Net.ExceptionBase.ThrowException(New Net.ExceptionConnectionServer With {.ServiceError = Me.LastError})


                            End Select

                        Case Else
                            TryDonwload = 0

                    End Select



                Loop Until TryDonwload = 0


                webClient.postParams.Clear()
                webClient.Multipart = False

                If Me.webClient.StatusCode <> 200 Then

                    Me.LastError.ResError = Res


                    Try
                        Dim Err As ServiceError
                        Err = MyApp.JSONDeserializeObj(Of ServiceError)(Res)

                        Me.LastError.Code = Err.code
                        Me.LastError.Message = Err.message

                    Catch ex As Exception

                        Me.LastError.Code = Me.webClient.StatusCode
                        Me.LastError.Message = Res

                    End Try

                    'https://bufferapp.com/developers/api/errors
                    Select Case Me.webClient.StatusCode

                        Case 400
                            Net.ExceptionBase.ThrowException(New Net.ExceptionAPIResponse With {.ServiceError = Me.LastError})


                        Case 403
                            Net.ExceptionBase.ThrowException(New Net.ExceptionAPIAccount With {.ServiceError = Me.LastError})

                    End Select




                    'End Select

                    Net.ExceptionBase.ThrowException(New Net.ExceptionBase With {.ServiceError = Me.LastError})

                End If


                Return Res

            End Function


            Public Function GetProfile(id As String) As Profile

                Dim Uri As New UriBuilder(SF("https://api.bufferapp.com/1/profiles/{0}.json", id))

                Dim queryString = HttpUtility.ParseQueryString("")

                'queryString.Add("format", "json")

                Uri.Query = queryString.ToString

                Dim Res = Me.Download(Uri.Uri.AbsoluteUri)
                'Return Res
                Return MyApp.JSONDeserializeObj(Of Profile)(Res)


            End Function

            Public Function GetProfiles() As List(Of Profile)

                Dim Uri As New UriBuilder(SF("https://api.bufferapp.com/1/profiles.json"))

                Dim queryString = HttpUtility.ParseQueryString("")

                'queryString.Add("format", "json")

                Uri.Query = queryString.ToString

                Dim Res = Me.Download(Uri.Uri.AbsoluteUri)
                'Return Res
                Return MyApp.JSONDeserializeObj(Of List(Of Profile))(Res)


            End Function

            Public Function PostUpdateCreate(ids As String, text As String) As UpdateResult

                Return Me.PostUpdateCreate(ids, text, Nothing)

            End Function

            Public Function PostUpdateCreate(ids As String, text As String, media As Dictionary(Of String, String)) As UpdateResult

                Dim Uri As New UriBuilder(SF("https://api.bufferapp.com/1/updates/create.json"))

                Dim queryString = HttpUtility.ParseQueryString("")

                webClient.postParams.Add("text", Net.WebClient.UrlEncode(text))
                webClient.postParams.Add("now", "true")
                'webClient.postParams.Add("top", "true")
                webClient.postParams.Add("shorten", "false")

                'shorten

                For Each id In ids.Split({","}, StringSplitOptions.RemoveEmptyEntries)
                    webClient.postParams.Add("profile_ids[]", id)
                Next

                If media IsNot Nothing Then
                    For Each m In media
                        webClient.postParams.Add("media[" & m.Key & "]", Net.WebClient.UrlEncode(m.Value))
                    Next
                End If


                'queryString.Add("format", "json")

                Uri.Query = queryString.ToString

                Dim Res = Me.Download(Uri.Uri.AbsoluteUri)
                'Return Res
                Return MyApp.JSONDeserializeObj(Of UpdateResult)(Res)


            End Function


        End Class
        Public Class ServiceError

            Public Property success As Boolean
            Public Property message As String
            Public Property code As Integer

        End Class
        Public Class Profile

            Public Property id As String
            Public Property avatar As String
            Public Property formatted_username As String

            Public Property service As String
            Public Property service_id As String
            Public Property service_username As String
            Public Property user_id As String


        End Class

        Public Class UpdateResult
            Public Property success As Boolean
            Public Property buffer_count As String
            Public Property updates As New List(Of Update)
        End Class

        Public Class Update

            Public Property id As String
            Public Property profile_service As String
            Public Property text As String
        End Class



    End Namespace
End Namespace


